const socket = io();

const $btn = $('#send') // 按钮
const $msgInput = $('#msg') // 输入框
const $chatMessages = $('.chat-messages') //消息列表
const $roomName = $('#room-name') //房间名字
const $userList = $('#users') //用户列表

// 依据URL获取用户登录的房间和用户名
const { username, room } = Qs.parse(location.search, {
    ignoreQueryPrefix: true
})

// 加入房间
socket.emit('joinRoom', { username, room })

// console.log(username, room)

// 获取从服务器发送的room和users
socket.on('roomUsers',({room,users})=>{
    outputRoomDetail(room,users)
})

// 获得从服务器发送的消息
// 监听message事件 on监听 emit触发
socket.on('message', (message) => {
    outputMessage(message);

    // 滚动条自动滚动到最下
    $chatMessages.scrollTop($chatMessages[0].scrollHeight)
    // 清除输入框的值
    $msgInput.val('')
    $msgInput.focus()
})


// 监听消息提交submit
$btn.on('click', (e) => {
    e.preventDefault()

    // 获取提交的消息
    const msg = cleanInput($msgInput.val().trim())
    socket.emit('chatMessage', msg)
})

// 创建 outputMessage 函数，输出消息到DOM，发送
const outputMessage = (msg) => {
    const div = `<div class='message'>
        <p class="meta">${msg.username}<span>${msg.time}</span></p>
        <p class="text">${msg.text}</p>
    </div>`
    $chatMessages.append(div)
}

// 输出房间信息
const outputRoomDetail = (room,users)=>{
    $roomName.text(room)
    // $userList.text("")
    // users.forEach(user => {
    //     $userList.append(`<li>${user.username}</li>`)
    // });
    $userList.html(`${users.map((user)=>`<li>${user.username}</li>`).join('')}`)
}

// 防止输入中插入标记
const cleanInput = (input) => {
    return $('<div/>').text(input).html()
}

const navigation = document.querySelector('.navigation');
document.querySelector('.toggle').onclick = function(){
    this.classList.toggle('active');
    navigation.classList.toggle('active');
}